<template>
  <el-dialog
    v-el-drag-dialog
    title="报修回访"
    :visible.sync="visible"
    width="800px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :model="temp" :rules="rules" label-position="right" label-width="100px" style="margin: 0 50px;">
      <el-form-item label="客户名称:">
        <el-input v-model="temp.csmName" disabled />
      </el-form-item>
      <el-form-item label="客户电话:">
        <el-input v-model="temp.contactPhone" disabled />
      </el-form-item>
      <el-form-item label="客户地址:" class="block">
        <el-input v-model="temp.contactAddress" disabled />
      </el-form-item>
      <el-form-item label="回访人:" prop="callUserName">
        <el-input v-model="temp.callUserName" />
      </el-form-item>
      <el-form-item label="回访日期:" prop="callTime">
        <el-date-picker
          v-model="temp.callTime"
          style="width: 100%;"
          type="date"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="回访结果:" prop="callResult" class="block">
        <el-select v-model="temp.callResult" style="width: 230px; margin-right: 10px;" placeholder="请选择" @change="callResultChange">
          <el-option
            v-for="item in visitStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
        <el-checkbox v-if="temp.callResult === 2" v-model="checked">转为投诉单</el-checkbox>
      </el-form-item>
      <el-form-item label="回访调查:" class="block">
        <el-checkbox-group v-model="checkedTypes">
          <el-checkbox v-for="item in commonKeysInfoList" :key="item.keyId" :value="item.keyId" :label="item.keyName" />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item v-if="temp.callResult === 2 && checked" label="处理机构:" prop="complainOrgId">
        <el-tree-select
          v-model="temp.complainOrgId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item v-if="temp.callResult === 2 && checked" label="处理人:" prop="userId">
        <el-select v-model="temp.userId" :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownerList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="block" label="处理说明:" prop="marker3">
        <el-input v-model="temp.marker3" type="textarea" :rows="3" maxlength="200" show-word-limit />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryRepairOrderVisitParam, queryRepairOrderReturnVisit, queryReturnOrderAuditorList } from '@/api'
  import moment from 'dayjs'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'

  export default {
    name: 'return-visit',
    data() {
      return {
        visible: false,
        visitStatusMap: [],
        commonKeysInfoList: [],
        checkedTypes: [],
        checked: false, // 转为投诉单
        currentOrg: null,
        treeData: [],
        ownerList: [],
        temp: {
          callUserName: '',
          callTime: moment(),
          callResult: 1,
          marker3: '',
          complainOrgId: -1,
          userId: ''
        },
        rules: {
          callUserName: [{ required: true, message: '请输入回访人', trigger: 'change' }],
          callTime: [{ required: true, message: '请输入回访日期', trigger: 'change' }],
          callResult: [{ required: true, message: '请选择回访结果', trigger: 'change' }],
          marker3: [{ required: true, message: '请输入处理说明', trigger: 'change' }],
          complainOrgId: [{ required: true, message: '请选择处理机构', trigger: 'change' }],
          userId: [{ required: true, message: '请选择处理人', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'orgList'
      ])
    },
    methods: {
      open(temp) {
        this.getDefaultData()
        this.getTreeData()
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp, {
              userId: ''
            })
            this.temp.callUserName = this.userInfo.userName
          }
        })
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.getOwnerList()
      },
      // 获取处理人列表
      async getOwnerList() {
        const orgId = this.currentOrg ? this.currentOrg.orgId : this.temp.complainOrgId
        const res = await queryReturnOrderAuditorList({
          orgId
        })
        this.ownerList = res.data
      },
      async getDefaultData() {
        const res = await queryRepairOrderVisitParam()
        this.visitStatusMap = JSON.parse(res.data.visitStatusMap)
        this.temp.callResult = 1
        this.commonKeysInfoList = JSON.parse(res.data.commonKeysInfoList)
      },
      // 回访结果如果选不满意 则显示转为投诉单复选框，如果勾选，则显示处理机构和处理人
      callResultChange(value) {
        if (value !== 2) this.checked = false
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const params = {
            callUserId: this.userInfo.userId,
            callUserName: this.temp.callUserName,
            callTime: moment(this.temp.callTime).format(),
            marker3: this.temp.marker3
          }
          if (this.checked && this.temp.complainOrgId) {
            const org = this.orgList.find(item => item.orgId === this.temp.complainOrgId)
            params.complainOrgId = org.orgId
            params.complainOrgSNNo = org.complainOrgSNNo
            params.complainOrgName = org.complainOrgName
            params.userId = this.temp.userId
          }
          let backVisitId = ''
          let backVisitDesc = ''// 回访描述
          this.checkedTypes.forEach(item => {
            const valueArray = item.split(',')
            backVisitId += valueArray[0] + ','
            backVisitDesc += ',' + valueArray[1]
          })
          params.repairCode = this.temp.repairCode
          params.csmCode = this.temp.csmCode
          params.callResult = this.temp.callResult
          params.callUserId = this.userInfo.userId
          params.callUserName = this.temp.callUserName
          params.callTime = moment(this.temp.callTime).format()
          params.marker3 = this.temp.marker3 + backVisitDesc
          this.submit(params, backVisitId, backVisitDesc)
        })
      },
      async submit(params, backVisitId, backVisitDesc) {
        await queryRepairOrderReturnVisit({
          json: params,
          backVisitId,
          backVisitDesc
        })
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功!',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.checkedTypes = []
        this.checked = false
        this.temp = {
          callUserName: '',
          callTime: moment(),
          callResult: 1,
          marker3: '',
          complainOrgId: -1,
          userId: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 50%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
